/**
 * 
 */
package com.pocketsweet.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.SignUpCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * @author bobhu 注册页面
 */
@ContentView(R.layout.activity_register_1)
public class Register extends Activity {

	@ViewInject(R.id.etPhoneNumber)
	private EditText etPhoneNumber;

	@ViewInject(R.id.etPassword)
	private EditText etPassword;

	@ViewInject(R.id.mainHeader)
	private HeaderLayout header;

	@ViewInject(R.id.btnClose)
	private ImageView btnClose;

	@ViewInject(R.id.btnShowPwd)
	private ImageView btnShowPwd;

	@ViewInject(R.id.tvProtocol)
	private TextView tvProtocol;

	private String password;
	private boolean isShowPwd = false;
	private LoadingDailog mLoadingDialog;
	private long mExitTime = 0;// 退出事件用到的事件


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		setHeaderFunction();
		initEdit();
	}

	private void initEdit() { // 监听输入框
		tvProtocol.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 打开协议网址
				Intent intent = new Intent(Register.this, WebViews.class);
				intent.putExtra("url", "http://www.pocketsweet.com/protocol");
				startActivity(intent);
			}
		});
		etPhoneNumber.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				if (!StringUtils.isEmpty(etPhoneNumber.getText().toString())) {
					btnClose.setVisibility(View.VISIBLE);
					btnClose.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							etPhoneNumber.setText("");
						}
					});
				} else {
					btnClose.setVisibility(View.GONE);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
		etPassword.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				if (!StringUtils.isEmpty(etPassword.getText().toString())) {
					btnShowPwd.setVisibility(View.VISIBLE);
					btnShowPwd.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							if (isShowPwd) {
								isShowPwd = false;
								// 设置密码为隐藏的
								btnShowPwd
										.setBackgroundDrawable(getResources()
												.getDrawable(
														R.drawable.icon_pwd_unshow));
								etPassword
										.setTransformationMethod(PasswordTransformationMethod
												.getInstance());
								if (etPassword.length() > 0) {
									etPassword.setSelection(etPassword.length());
								}
							} else { // 设置EditText的密码为可见的
								isShowPwd = true;
								btnShowPwd.setBackgroundDrawable(getResources()
										.getDrawable(R.drawable.icon_pwd_show));
								etPassword
										.setTransformationMethod(HideReturnsTransformationMethod
												.getInstance());
								if (etPassword.length() > 0) {
									etPassword.setSelection(etPassword.length());
								}

							}
						}
					});
				} else {
					btnShowPwd.setVisibility(View.GONE);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("下一步");
		header.setMiddleText("注册");
		header.setRighttContainerClickListener(new onRightContainerListener() {
			@Override
			public void onClick() {
				// ToolKits.toast(this, "点击了按键");
				mLoadingDialog = ToolKits.createLoadingDialog(Register.this,
						"验证中...");
				mLoadingDialog.setText("请稍等");
				String mobile = etPhoneNumber.getText().toString().trim();
				password = etPassword.getText().toString().trim();
				// if (!ToolKits.isMobileNum(mobile)) {
				// // 弹出提示，不是正确的手机号
				// ToolKits.toast(this, R.string.mobile_format);
				// return;
				// }
				if (TextUtils.isEmpty(mobile)) {
					ToolKits.toast(Register.this, "手机号码不能为空");
					return;
				}
				if (TextUtils.isEmpty(password) || password.length() < 6
						|| password.length() > 16) {

					ToolKits.toast(Register.this, R.string.password_hint);
					return;
				}
				mLoadingDialog.show();
				// 验证手机去
				try {
					UserService.signUp(mobile, password, mobile,
							new SignUpCallback() {
								@Override
								public void done(AVException e) {
									if (e != null) {
										mLoadingDialog.dismiss();
//										Log.e("=register",
//												"error " + e.getMessage());

										if (e.getCode() == 107) {// leancloud
																	// 内部解析错误
											ToolKits.toast(Register.this,
													"注册失败，请稍后重试");
										} else {
											ToolKits.toast(Register.this,
													"账号已存在,请直接登录");
										}
										return;
									} else {
										// // 如果注册没有错误跳转到验证
										Intent verifyInent = new Intent(
												Register.this,
												VerifySmsCode.class);
										// CreateUserInfo.class);
										Register.this
												.startActivity(verifyInent);
										ToolKits.toast(Register.this,
												R.string.verify_sms_code_send);
									}
								}
							});
				} catch (AVException e) {
					e.printStackTrace();
//					Log.e("=register", "register failed" + e.getMessage());
				}

			}
		});
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				Intent intent = new Intent(Register.this, Login.class);
				startActivity(intent);
				Register.this.finish();
			}
		});
	}

	// 用户已经有了账号跳转到登陆页面
	/*
	 * @OnClick(R.id.tvHasAccount) public void alreadyHasAccount(View view) {
	 * Intent loginIntent = new Intent(this, Login.class);
	 * startActivity(loginIntent); }
	 */

	// 点击版权 和 协议
	public void onCopyRightClick() {
		Toast.makeText(this, "onCopyRightClick", Toast.LENGTH_LONG).show();
	}

	/**
	 * 重写onKeyDown方法
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitAlet();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showExitAlet() {
		if ((System.currentTimeMillis() - mExitTime) > 2000) {
			Toast toast = Toast.makeText(Register.this, "再按一次退出程序",
					Toast.LENGTH_LONG);
			// 可以控制toast显示的位置
			toast.setGravity(Gravity.BOTTOM, 0, 150);
			toast.show();
			mExitTime = System.currentTimeMillis();

		} else {
			Register.this.finish();
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
